/*
 * Copyright 2014 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hiva.gmovie.reader;

import com.hiva.gmovie.domain.MovieTheater;
import com.hiva.gmovie.domain.Showtime;
import com.hiva.gmovie.util.Constants;
import com.hiva.gmovie.util.ExtractorHelper;
import java.util.ArrayList;
import java.util.List;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.awt.windows.ThemeReader;

/**
 * Utility class to read the movie theater information.
 * @author Rivaldo
 */
public class MovieTheaterReader {
    
    private static final Logger LOG = LoggerFactory.getLogger(MovieTheaterReader.class);
    
    public List<MovieTheater> getMovieTheater(Source source) {
        
        LOG.trace("Accessing theater tag");
        List<Element> allElements = source.getAllElements(Constants.THEATER);
        
        List<MovieTheater> theater = new ArrayList<MovieTheater>();
        
        for (Element element : allElements) {
            theater.add(getMovieTheaterDescription(element));
        }
        
        return theater;
    }
    
    private MovieTheater getMovieTheaterDescription(Element theaterTag) {
        
        LOG.debug("Accessing theater description tag");
        List<Element> theaterDescTag = theaterTag.getAllElements(Constants.THEATER_DESC);
        
        String name = ExtractorHelper.getTagText(theaterDescTag.get(0), Constants.THEATER_DESC_NAME);
        String info = ExtractorHelper.getTagText(theaterDescTag.get(0), Constants.THEATER_DESC_INFO);
        
        List<Showtime> showtime = getShowtime(theaterTag);
        
        return new MovieTheater(name, info, showtime);
    }
    
    private List<Showtime> getShowtime(Element theaterTag) {
        
        LOG.debug("Accessing showtime tag");
        List<Element> showTimeTag = theaterTag.getAllElements(Constants.THEATER_SHOWTIME);
        
        List<Showtime> showtime = new ArrayList<Showtime>();
        ShowtimeReader reader = new ShowtimeReader();
        
        if (showTimeTag != null && showTimeTag.size() > 0) {
            showtime = reader.readShowtime(showTimeTag.get(0));
        }
        
        return showtime;
    }
    
}
